package com.xiecong.aspect;

import com.xiecong.mapper.LoginLogMapper;
import com.xiecong.pojo.Emp;
import com.xiecong.pojo.EmpLoginLog;
import com.xiecong.pojo.LoginInfo;
import com.xiecong.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Aspect
@Component
public class LoginLoginAspect {

    @Autowired
    private LoginLogMapper loginLogMapper;

    @Around("execution(* com.xiecong.controller.LoginController.login(..))")
    public Object recordLoginLog(ProceedingJoinPoint pjp) throws Throwable {
        log.info("开始记录登录日志");
        // 创建登录日志对象
        EmpLoginLog empLoginLog = new EmpLoginLog();
        // 获取开始操作时间
        long startTime = System.currentTimeMillis();
        // 获取参数 public Result login(@RequestBody Emp emp)
        Object[] args = pjp.getArgs();
        Object arg = args[0];
        // 强转为Emp类型
        Emp emp = (Emp) arg;
        // 获取username和password并设置到empLoginLog对象中
        empLoginLog.setUsername(emp.getUsername());
        empLoginLog.setPassword(emp.getPassword());
        try {
            // 调用原始方法
            Object result = pjp.proceed();
            // 将result从Object强转为Result类型 public Result login(@RequestBody Emp emp)
            Result loginResult = (Result) result;
            // 获取结果码并设置到empLoginLog对象中
            empLoginLog.setIsSuccess((loginResult.getCode().shortValue()));
            // 如果登录成功获取token/jwt
            if (loginResult.getCode() == 1) {
                Object data = loginResult.getData();
                // 强转为LoginInfo类型
                LoginInfo loginInfo = (LoginInfo) data;
                // 获取token并设置到empLoginLog对象中
                empLoginLog.setJwt(loginInfo.getToken());
            } else {
                empLoginLog.setJwt(loginResult.getMsg());
            }
            return result;
        } catch (Throwable e) {
            empLoginLog.setIsSuccess((short) 0);
            empLoginLog.setJwt("出现未知异常！");
            throw e;
        } finally {
            // 获取登录时间并设置到empLoginLog对象中
            empLoginLog.setLoginTime(LocalDateTime.now());
            // 获取结束操作时间，计算出耗时并设置到empLoginLog对象中
            long end = System.currentTimeMillis();
            empLoginLog.setCostTime(end - startTime);
            // 插入登录日志
            loginLogMapper.insert(empLoginLog);
        }
    }
}
